package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
public class OrderController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;


    @RequestMapping("/order/submit")
    // /order/submit
    //后台提交参数 和类不匹配，所以用 Map连接
    public Result submit(@RequestBody Map orderInfo) throws ClientException {
        String telephone = (String)orderInfo.get("telephone");
        String s = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) orderInfo.get("validateCode");

        // 检查 验证码是否正确
        if( s == null || validateCode==null  || !s.equals(validateCode)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //最好将该参数立马设置为null,或者是删除该方法

        //设置预约类型为微信预约

        orderInfo.put("orderType",Order.ORDERTYPE_WEIXIN);

        // 将 传来的信息 加入数据库；
        Result result = orderService.submit(orderInfo);
        //判断是否预约成功，
        System.out.println(result.isFlag());
        if(result.isFlag()){
            telephone = (String)orderInfo.get("telephone");
            System.out.println(telephone);
            //已经预约成功，发送短信 telephone ，暂时隐藏
//            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,"预约成功");

            System.out.println("发送预约成功短信成功");
        }
        return result;
    }

    //体检预约信息的返回
    //  /order/findById
    @RequestMapping("/order/findById")
    public Result findById(Integer id){
        return orderService.findById(id);
    }

}
